package com.spring4all.service.impl;

import com.spring4all.constant.RoleConstant;
import com.spring4all.entity.UserEntity;
import com.spring4all.mapper.UserMapper;
import com.spring4all.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

@Service
@Primary
//@Log4j
public class BaseUserService implements UserService {
	
	
    private final UserMapper userMapper;
    
    @Autowired
    public BaseUserService(UserMapper userMapper){
        this.userMapper = userMapper;
    }

    @Override
    public String insert(UserEntity userEntity) {
        String username = userEntity.getUsername();
        if (exist(username))
            return "found";
        if ("".equals(username.trim()) || "".equals(userEntity.getPassword())) {
			return "nodata";
		}
        //对密码进行BCrypt加密
        String hashed = BCrypt.hashpw(userEntity.getPassword(), BCrypt.gensalt());
        userEntity.setPassword(hashed);
        System.out.println(hashed);
        
        userEntity.setRoles(RoleConstant.ROLE_USER);
        userMapper.insert(userEntity);
        return  "succuss";
    }

    @Override
    public UserEntity getByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    /**
     * 判断用户是否存在
     * @param username 账号
     * @return 密码
     */
    private boolean exist(String username){
        UserEntity userEntity = userMapper.selectByUsername(username);
        return (userEntity != null);
    }

}
